package org.example.webservice.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.example.webservice.feign.AiServiceClient;
import org.example.webservice.feign.FileServiceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Controller
public class WebController {

    @Autowired
    private FileServiceClient fileServiceClient;

    @Autowired
    private AiServiceClient aiServiceClient;

    @GetMapping("/")
    public String index(Model model) {
        try {
            // 获取文件列表
            String fileListJson = fileServiceClient.getFileList();
            
            // 验证返回的JSON字符串
            if (fileListJson == null || fileListJson.trim().isEmpty()) {
                System.out.println("警告：文件服务返回空响应");
                model.addAttribute("files", new java.util.ArrayList<>());
                return "index";
            }
            
            // 解析JSON
            JSONObject fileListResult = JSON.parseObject(fileListJson);
            if (fileListResult == null) {
                System.out.println("警告：无法解析文件服务响应为JSON");
                model.addAttribute("files", new java.util.ArrayList<>());
                return "index";
            }
            
            // 获取数据
            Object filesData = fileListResult.get("data");
            if (filesData != null) {
                model.addAttribute("files", filesData);
                System.out.println("成功获取文件列表，数量：" + 
                    (filesData instanceof java.util.List ? ((java.util.List<?>) filesData).size() : "未知"));
            } else {
                System.out.println("警告：文件服务响应中没有data字段");
                model.addAttribute("files", new java.util.ArrayList<>());
            }
            
        } catch (Exception e) {
            System.err.println("获取文件列表时发生错误：" + e.getMessage());
            e.printStackTrace();
            model.addAttribute("files", new java.util.ArrayList<>());
            // 添加错误信息到模型，以便在页面上显示
            model.addAttribute("errorMessage", "无法连接到文件服务，请检查服务是否正常运行");
        }
        return "index";
    }

    @PostMapping("/upload")
    @ResponseBody
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            String response = fileServiceClient.uploadFile(file);
            JSONObject responseJson = JSON.parseObject(response);
            result.put("success", responseJson.getBoolean("success"));
            result.put("message", responseJson.getString("message"));
            result.put("data", responseJson.get("data"));
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "上传失败: " + e.getMessage());
        }
        return result;
    }

    @PostMapping("/chat")
    @ResponseBody
    public Map<String, Object> chat(@RequestParam Long fileId, @RequestParam String question) {
        Map<String, Object> result = new HashMap<>();
        try {
            String response = aiServiceClient.chat(fileId, question);
            JSONObject responseJson = JSON.parseObject(response);
            result.put("success", responseJson.getBoolean("success"));
            result.put("answer", responseJson.getString("answer"));
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "对话失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 健康检查端点
     */
    @GetMapping("/health")
    @ResponseBody
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("timestamp", System.currentTimeMillis());
        
        // 检查文件服务连接
        try {
            String fileListJson = fileServiceClient.getFileList();
            result.put("fileService", "UP");
            result.put("fileServiceResponse", fileListJson != null ? "OK" : "NULL");
        } catch (Exception e) {
            result.put("fileService", "DOWN");
            result.put("fileServiceError", e.getMessage());
        }
        
        // 检查AI服务连接
        try {
            // 这里可以添加AI服务的健康检查
            result.put("aiService", "UNKNOWN");
        } catch (Exception e) {
            result.put("aiService", "DOWN");
            result.put("aiServiceError", e.getMessage());
        }
        
        return result;
    }
    /**
     * 清空所有文件（转发到 file-service）
     */
    @DeleteMapping("/api/files/clear")
    @ResponseBody
    public Map<String, Object> clearAllFiles() {
        Map<String, Object> result = new HashMap<>();
        try {
            String response = fileServiceClient.clearAllFiles();
            com.alibaba.fastjson.JSONObject responseJson = com.alibaba.fastjson.JSON.parseObject(response);
            result.put("success", responseJson.getBoolean("success"));
            result.put("message", responseJson.getString("message"));
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "清空失败: " + e.getMessage());
        }
        return result;
    }
}